# Create your views here.

import datetime
import time

from django import forms
from django.contrib.auth.decorators import login_required
from django.shortcuts import HttpResponse, redirect, render
from django.urls import reverse

from cdserver.utils.pagination import Pagenation
from logview.utils import logger

from ..models import ReleaseInfo


class DraftModelForm(forms.ModelForm):
    class Meta:
        model = ReleaseInfo
        exclude = ("create_time", "status")
        # fields = "__all__"

        widgets = {
            "product_name": forms.TextInput(attrs={"class": "input"}),
            "release_version": forms.TextInput(attrs={"class": "input"}),
            "release_remarks": forms.Textarea(attrs={"class": "textarea", "rows": "1"}),
            "update_front": forms.Textarea(attrs={"class": "textarea", "rows": "5"}),
            "update_back": forms.Textarea(attrs={"class": "textarea", "rows": "5"}),
            "fixed_front": forms.Textarea(attrs={"class": "textarea", "rows": "5"}),
            "fixed_back": forms.Textarea(attrs={"class": "textarea", "rows": "5"}),
            "problems": forms.Textarea(attrs={"class": "textarea", "rows": "5"}),
            "hash_front": forms.TextInput(attrs={"class": "input"}),
            "hash_back": forms.TextInput(attrs={"class": "input"}),
        }


@login_required
def draft_list(request):
    """发版草稿查询"""
    from django.db.models import Q

    queryset = ReleaseInfo.objects.filter(Q(status=1) | Q(status=3), deleted_at=None)
    page_object = Pagenation(request, queryset)
    context = {
        "object_list": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "draft/draft_list.html", context)


@login_required
def draft_view(request, nid):
    """查看发版草稿"""
    # 获取数据库对象
    row_obj = ReleaseInfo.objects.get(id=nid)
    return render(request, "draft/draft_view.html", {"row": row_obj})


@login_required
def draft_delete(request, nid):
    """删除发版草稿"""
    # 删除数据库对象
    ri = ReleaseInfo.objects.get(id=nid)
    ri.deleted_at = datetime.datetime.now()
    ri.save()
    logger.info(f"<User {request.user.username}> remove <ReleaseInfo {ri.id}>")
    return redirect(reverse("draft_list"))


@login_required
def draft_edit(request, nid):
    """更新发版草稿"""
    # 获取数据库对象
    row_obj = ReleaseInfo.objects.filter(id=nid).first()

    if row_obj.status != 1:
        return render(request, "draft/draft_edit.html", {"error": "不允许修改"})

    # GET
    if request.method == "GET":
        form = DraftModelForm(instance=row_obj)
        return render(request, "draft/draft_edit.html", {"form": form})
    # Request Post
    form = DraftModelForm(data=request.POST, instance=row_obj)
    form.create_time = time.strftime("%Y-%m-%d", time.localtime(time.time()))

    # 数据校验
    if form.is_valid():
        form.save()
        return redirect("/draft/list/")
    # 校验失败
    return render(request, "draft/draft_edit.html", {"form": form})
